<?php

class DbHelper 
{
    
    public static function getDb()
    {
        return DBManagerFactory::getInstance();
    }
    
    public static function insert($row, $table)
    {
        $sql  = "INSERT INTO $table (`";
        $sql .= implode("`,`", array_keys($row));
        $sql .= "`) VALUES ('";
        $sql .= implode("','", array_values($row));
        $sql .= "')";
        
        return self::getDb()->query($sql);
    }
    
    public function update($table, $values, $where)
    {
        $sql = "UPDATE $table SET ";
        
        $cnt = count($values);
        $i   = 1;
        foreach ($values as $key => $val) {
            $sql .= " `$key` = '$val' ";
            if ($i < $cnt) {
                $sql .= ", ";
            }
            $i++;
        }
        
        $sql .= " WHERE ";
        
        $cnt = count($where);
        $i   = 1;
        foreach ($where as $key => $val) {
            $sql .= " `$key` = '$val' ";
            if ($i < $cnt) {
                $sql .= " AND ";
            }
            $i++;
        }
        
        return self::getDb()->query($sql);
    }
    
    public static function fetchOne($sql)
    {
        $result = self::getDb()->query($sql);
        return self::getDb()->fetchByAssoc($result);
    }
    
    public static function fetchAll($sql, $column = '')
    {
        $data   = array();
        $result = self::getDb()->query($sql);
        
        while($row = self::getDb()->fetchByAssoc($result) ){
            $data[] = empty($column)? $row: $row[$column];
        }
        
        return $data;
    }
    
    public static function fetchPairs($sql, $key, $val)
    {
        $data   = array();
        $result = self::getDb()->query($sql);
        
        while($row = self::getDb()->fetchByAssoc($result) ) {
            $data[$row[$key]] = $row[$val];
        }
        
        return $data;
    }
}